layui.use(['upload', 'element', 'layer', 'form'], function(){
  var $ = layui.jquery
  ,upload = layui.upload
  ,element = layui.element
  ,layer = layui.layer
  ,form = layui.form;

  // 个人信息页展示
  $.ajax({
    type: 'GET',
    url: '/user/detail/',
    headers: {
      Authorization: localStorage.getItem('Authorization')
    },
    success: function(msg){
      // console.log(msg);
      let detail = msg.data.detail
      $("#portrait_t").attr('src', detail.portrait);
      if (msg.code != 0){
        location.href = '/static/index.html'
      }else{
        if (detail.nickname){
          nickname = detail.nickname
        }else{
          nickname = msg.data.email
        }
        $('input[name="nickname"]').val(nickname);
        $('input[name="age"]').val(detail.age);
        $("input[name='bth']").val(detail.bth);
        $("input[name='phone']").val(detail.phone);
        $("input[name='addr']").val(detail.addr);
        $("textarea[name='ps']").val(detail.ps);
        if (detail.sex == 0){
          $("input[name='sex'][value='0']").prop('checked',true);
        }else{
          $("input[name='sex'][value='1']").prop('checked',true);
        }
        form.render();
      }
      $("#nickname").html(nickname);
    }
  });

  //拖拽上传
  upload.render({
    elem: '#file'
    ,url: '/user/portrait/' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
    ,headers: {
        Authorization: localStorage.getItem('Authorization')
      },
    done: function(res){
      layer.msg('上传成功');
      $('#upload').removeClass('layui-hide').find('img').attr('src', res.data);
      // console.log(res.data);
      $("#portrait_t").attr('src', res.data);
    }
  });

  // 监听提交
  form.on('submit(info)', function(data){
    $.ajax({
      type: 'POST',
      url: '/user/detail/',
      headers: {
        Authorization: localStorage.getItem('Authorization')
      },
      data: data.field,
      success: function(msg){
        $("#nickname").html($("input[name='nickname']").val());
      }
    });
    return false;
  });

  //自定义验证规则
  form.verify({
    phone: [/^[1][3-9][0-9]{9}$/, '11位有效手机号']
    ,age: [
      /^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$/
      ,'年龄必须是数字，且不超过180'
    ]
  });

});